'use strict'

class smart {
  constructor() {
    this.param = '/'
  }

  async post(c) {
    // 得到用户输入内容
    const str = c.body.content
    // 拿到简要数据库，加入分数属性
    let ret = await c.service.psql.query(`select smart_id, smart_tag from smart`)
    let rows = ret.rows
    for (let i = 0; i < rows.length; i++) {
      rows[i].score = 0
    }
    // 分割字符串，单字匹配
    let strArr = str.split('')
    console.log(strArr)
    // 单字匹配记录分数，山峰得分法
    strArr.forEach(value => {
      for (let i = 0; i < rows.length; i++) {
        let index = rows[i].smart_tag.indexOf(value)
        let len = rows[i].smart_tag.length
        if (index != -1) {
          let score = (len + 0.4) / 2 - Math.abs(index / len - len / 2)
          score *= 10
          rows[i].score += score
        }
      }
    });
    // 双字匹配记录分数，匹配数权重法
    for (let i = 0; i < strArr.length - 1; i++) {
      let tempStr = strArr[i] + strArr[i + 1]
      let countNum = 0
      let shouldChangeScoreArr = []
      for (let i = 0; i < rows.length; i++) {
        let index = rows[i].smart_tag.indexOf(tempStr)
        if (index != -1) {
          countNum++
          shouldChangeScoreArr.push(i)
        }
      }
      let shouldAddedScore = countNum == 0 ? 0 : rows.length / countNum
      shouldChangeScoreArr.forEach(value => {
        rows[value].score += shouldAddedScore
      })
      console.log(tempStr, countNum, shouldChangeScoreArr, shouldAddedScore)
    }

    // 精确index，精确id
    let smart_index_exact = 0
    let smart_id_exact = 0
    // 取最高分
    rows.forEach((value, index) => {
      if (value.score >= rows[smart_index_exact].score) {
        smart_index_exact = index
      }
    })
    // 4分以下令本次匹配判为失败
    if (rows[smart_index_exact].score <= 4) {
      smart_id_exact = '10000001'
    } else {
      smart_id_exact = rows[smart_index_exact].smart_id
    }
    let ret2 = await c.service.psql.query(`select smart_content from smart where smart_id like '${smart_id_exact}'`)
    let row_exact = ret2.rows
    console.log(row_exact)
    c.status(200).send({ rows, content_exact: row_exact[0].smart_content })
  }
}

module.exports = smart